package com.studyroom.controller;

import com.studyroom.common.Result;
import com.studyroom.dto.SeatDTO;
import com.studyroom.dto.TimeRangeDTO;
import com.studyroom.entity.Seat;
import com.studyroom.service.SeatService;
import com.studyroom.vo.ReservationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/seats")
public class SeatController {
    
    @Autowired
    private SeatService seatService;
    
    @GetMapping("/available/{roomId}")
    public Result<List<SeatDTO>> getAvailableSeats(@PathVariable Integer roomId) {
        return Result.success(seatService.getAvailableSeats(roomId));
    }


    public SeatController(SeatService seatService) {
        this.seatService = seatService;
    }

    @GetMapping("/room/{roomId}")
    public Result<List<Seat>> getByRoomId(@PathVariable Long roomId) {
        return Result.success(seatService.getByRoomId(roomId));
    }

    @PutMapping("/{id}")
    public Result<?> update(@PathVariable Long id, @RequestBody Seat seat) {
        seat.setId(id);
        seatService.updateById(seat);
        return Result.success();
    }

    @PostMapping("/{seatId}/reservations")
    public Result getReservations(
            @PathVariable Long seatId,
            @RequestBody TimeRangeDTO timeRange
    ) {
        List<ReservationVO> reservations = seatService.getReservations(
                seatId,
                timeRange.getStartTime(),
                timeRange.getEndTime(),
                Arrays.asList(1, 2)
        );
        return Result.success(reservations);
    }

    @GetMapping("/admin/study-rooms/{roomId}/seats")
    public Result<List<Seat>> getSeatsByRoomId(@PathVariable Long roomId) {
        return Result.success(seatService.getByRoomId(roomId));
    }

    /**
     * 更新座位状态
     */
    @PutMapping("/admin/study-rooms/{roomId}/seats/{seatId}")
    public Result<Boolean> updateSeatStatus(
            @PathVariable Long roomId,
            @PathVariable Long seatId,
            @RequestBody Map<String, Integer> params) {
        
        // 获取available参数
        Integer available = params.get("available");
        if (available == null) {
            return Result.error("参数错误");
        }
        
        try {
            // 使用专门的方法更新座位状态
            boolean result = seatService.updateSeatStatus(seatId, available);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("更新座位状态失败: " + e.getMessage());
        }
    }
} 